package com.paishen.peiniwan.module.profile;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMChatManager;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.LogUtil;
import com.paishen.common.widget.MaterialHeader;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.AuthInfoDao;
import com.paishen.peiniwan.database.PhotoDao;
import com.paishen.peiniwan.database.User;
import com.paishen.peiniwan.database.util.ModelConverter;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.Photo;
import com.paishen.peiniwan.frame.http.entity.UserMiscInfo;
import com.paishen.peiniwan.frame.http.entity.UserTag;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

public class MainProfileLayout extends FrameLayout {

    private long clickTimestamp, requestTimestamp;

    public interface OnProfileMenuClickListener {
        void onEditClick();

        void onAlbumClick();

        void onDateClick();

        void onBalanceClick();

        void onConcernClick();

        void onFansClick();

        void onAuthClick();

        void onSysSettingsClick();
    }

    private OnProfileMenuClickListener callback;

    public void setOnProfileMenuClickListener(OnProfileMenuClickListener callback) {
        this.callback = callback;
    }

    final int switchTabToRefreshTime = 30 * 1000;

    private final PtrFrameLayout layPtrFrame;
    private final TextView txPercent;
    private final ImageView imgAvatar;
    private final View layAlbumInfo, txAlbumInfo;
    private final ImageView imgPhoto1, imgPhoto2, imgPhoto3, imgPhoto4;
    private final View viewDateInfo, layPercent;
    private final TextView txAuthInfo;
    private final TextView txNickname, txIntro;
    private final TextView txFans, txConcern, txBalance;

    private final AuthInfoDao authInfoDao;
    private final String[] profileValidStatusValue;

    public MainProfileLayout(Context context) {
        this(context, null);
    }

    public MainProfileLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.layout_main_profile, this);
        setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);

        authInfoDao = App.i().getCurrDaoSession().getAuthInfoDao();
        profileValidStatusValue = getResources().getStringArray(R.array.profile_auth_status_value);

        // final ScrollView viewScroll = (ScrollView) findViewById(R.id.view_scroll);
        final View layContainer = findViewById(R.id.lay_container);
        layPtrFrame = (PtrFrameLayout) findViewById(R.id.lay_ptr_frame);
        MaterialHeader header = new MaterialHeader(getContext());
        int[] colors = new int[]{0xFF05131A};
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPadding(0, BaseUtil.dip2px(15), 0, BaseUtil.dip2px(10));
        header.setPtrFrameLayout(layPtrFrame);
        layPtrFrame.setDurationToCloseHeader(1500);
        layPtrFrame.setHeaderView(header);
        layPtrFrame.addPtrUIHandler(header);
        layPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, layContainer, header);
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                requestUserMiscInfo();
            }
        });

        imgAvatar = (ImageView) findViewById(R.id.img_avatar);
        imgAvatar.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), ProfileInfoActivity.class);
                intent.putExtra(ProfileInfoActivity.EXTRA_SHOWN_USER_ID, App.i().getUser().getId());
                getContext().startActivity(intent);
            }
        });

        txIntro = (TextView) findViewById(R.id.tx_intro);
        txBalance = (TextView) findViewById(R.id.tx_balance);
        txFans = (TextView) findViewById(R.id.tx_fans);
        txConcern = (TextView) findViewById(R.id.tx_concern);

        layAlbumInfo = findViewById(R.id.lay_album_info);
        txAlbumInfo = findViewById(R.id.tx_album_info);
        imgPhoto1 = (ImageView) findViewById(R.id.img_photo_1);
        imgPhoto2 = (ImageView) findViewById(R.id.img_photo_2);
        imgPhoto3 = (ImageView) findViewById(R.id.img_photo_3);
        imgPhoto4 = (ImageView) findViewById(R.id.img_photo_4);

        viewDateInfo = findViewById(R.id.view_date_info);
        txAuthInfo = (TextView) findViewById(R.id.tx_auth_info);

        txNickname = (TextView) findViewById(R.id.tx_nickname);
        txPercent = (TextView) findViewById(R.id.tx_percent);
        layPercent = findViewById(R.id.lay_percent);

        final OnClickListener onProfileMenuClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                final long currClickTimestamp = System.currentTimeMillis();
                if (currClickTimestamp - clickTimestamp < 800) {
                    return;
                } else {
                    clickTimestamp = currClickTimestamp;
                }

                if (callback != null) {
                    switch (v.getId()) {
                        case R.id.lay_balance:
                            callback.onBalanceClick();
                            break;
                        case R.id.lay_concern:
                            callback.onConcernClick();
                            break;
                        case R.id.lay_fans:
                            callback.onFansClick();
                            break;
                        case R.id.lay_percent:
                            callback.onEditClick();
                            break;
                        case R.id.lay_album:
                            callback.onAlbumClick();
                            break;
                        case R.id.lay_date:
                            callback.onDateClick();
                            break;
                        case R.id.lay_auth:
                            com.paishen.peiniwan.database.AuthInfo dbAuthInfo = authInfoDao.queryBuilder().where(AuthInfoDao.Properties.UserId.eq(App.i().getUser().getId())).unique();
                            if (dbAuthInfo != null) {
                                final String status = dbAuthInfo.getStatus();
                                if (!TextUtils.equals(status, profileValidStatusValue[1])) {
                                    callback.onAuthClick();
                                }
                            }
                            break;
                        case R.id.lay_sys_settings:
                            callback.onSysSettingsClick();
                            break;
                    }
                }
            }
        };

        findViewById(R.id.lay_balance).setOnClickListener(onProfileMenuClickListener);
        findViewById(R.id.lay_concern).setOnClickListener(onProfileMenuClickListener);
        findViewById(R.id.lay_fans).setOnClickListener(onProfileMenuClickListener);
        findViewById(R.id.lay_percent).setOnClickListener(onProfileMenuClickListener);
        findViewById(R.id.lay_album).setOnClickListener(onProfileMenuClickListener);
        findViewById(R.id.lay_date).setOnClickListener(onProfileMenuClickListener);
        findViewById(R.id.lay_auth).setOnClickListener(onProfileMenuClickListener);
        findViewById(R.id.lay_sys_settings).setOnClickListener(onProfileMenuClickListener);


        initData(false);
        initAlbumPhoto(true);

        requestUserMiscInfo();
    }

    public void initData(boolean byInternetRequest) {
        if (!byInternetRequest) {
            // refreshBaseInfo 陪丸 粉丝 关注 昵称
            User u = App.i().getUser();
            Glide.with(getContext()).load(u.getHead_img_url()).bitmapTransform(App.i().getCropCircleTransformation()).placeholder(R.mipmap.common_avatar_c_170).into(imgAvatar);
            txNickname.setText(u.getNickname());
            txIntro.setText(u.getIntro());
            txBalance.setText(String.valueOf((int) u.getAmount().floatValue()));
            txConcern.setText(String.valueOf(u.getConcern()));
            txFans.setText(String.valueOf(u.getFans()));
            //资料完整度
            int restIntegrity = calcUserDataIntegrity(u);
            layPercent.setVisibility(restIntegrity >= 100 ? View.GONE : View.VISIBLE);
            if (layPercent.getVisibility() == View.VISIBLE) {
                txPercent.setText(restIntegrity + "%");
                int dateInfoPercentResId;
                switch (restIntegrity / 10) {
                    default:
                        dateInfoPercentResId = R.mipmap.date_info_percent_30;
                        break;
                    case 4:
                        dateInfoPercentResId = R.mipmap.date_info_percent_40;
                        break;
                    case 5:
                        dateInfoPercentResId = R.mipmap.date_info_percent_50;
                        break;
                    case 6:
                        dateInfoPercentResId = R.mipmap.date_info_percent_60;
                        break;
                    case 7:
                        dateInfoPercentResId = R.mipmap.date_info_percent_70;
                        break;
                    case 8:
                        dateInfoPercentResId = R.mipmap.date_info_percent_80;
                        break;
                    case 9:
                        dateInfoPercentResId = R.mipmap.date_info_percent_90;
                        break;
                }
                txPercent.setBackgroundResource(dateInfoPercentResId);
            }
            // 认证信息
            com.paishen.peiniwan.database.AuthInfo dbAuthInfo = authInfoDao.queryBuilder().where(AuthInfoDao.Properties.UserId.eq(App.i().getUser().getId())).unique();
            if (dbAuthInfo != null) {
                final String status = dbAuthInfo.getStatus();
                String[] profileValidStatusValue = getResources().getStringArray(R.array.profile_auth_status_value);
                txAuthInfo.setText(status);
                txAuthInfo.setVisibility(View.VISIBLE);
                if (TextUtils.equals(status, profileValidStatusValue[0]) || TextUtils.equals(status, profileValidStatusValue[3])) {
                    txAuthInfo.setTextColor(0xFFFC4E52);
                } else if (TextUtils.equals(status, profileValidStatusValue[1]) || TextUtils.equals(status, profileValidStatusValue[2])) {
                    txAuthInfo.setTextColor(0xFFB3B3B3);
                } else {
                    txAuthInfo.setVisibility(View.GONE);
                }
            }
        } else {
            final long currClickTimestamp = System.currentTimeMillis();
            if (currClickTimestamp - requestTimestamp < switchTabToRefreshTime) {
                return;
            } else {
                requestTimestamp = currClickTimestamp;
            }

            requestUserMiscInfo();
        }
    }

    private void requestUserMiscInfo() {
        PnwHttpManager.User.miscInfo(((BaseActivity) getContext()).TAG, new PnwOkCallbackAdapter<HttpRespData<UserMiscInfo>>() {
            @Override
            public void onResponse(HttpRespData<UserMiscInfo> response, boolean fresh) {
                super.onResponse(response, fresh);
                layPtrFrame.refreshComplete();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    int activeDateCount = response.data.orderCount;
                    viewDateInfo.setVisibility(activeDateCount > 0 ? View.VISIBLE : View.INVISIBLE);

                    com.paishen.peiniwan.database.AuthInfo dbAuthInfo = authInfoDao.queryBuilder().where(AuthInfoDao.Properties.UserId.eq(App.i().getUser().getId())).unique();
                    dbAuthInfo = ModelConverter.mergeOrReplace(dbAuthInfo, response.data.auth, App.i().getUser().getId());
                    authInfoDao.insertOrReplace(dbAuthInfo);

                    User login = App.i().getUser();
                    login.setAmount(response.data.goldAmount);
                    login.setConcern(response.data.collectCount);
                    login.setFans(response.data.fansCount);
                    EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, login));

                    initData(false);
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    LogUtil.e("MainProfileLayout requestUserMiscInfo() /n" + response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                layPtrFrame.refreshComplete();
                //
            }
        });
    }

    private void requestUserGetPhoto() {
        PnwHttpManager.User.getPhoto(((BaseActivity) getContext()).TAG, App.i().getUser().getId(), new PnwOkCallbackAdapter<HttpRespData<List<Photo>>>() {
            @Override
            public void onResponse(HttpRespData<List<Photo>> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    PhotoDao photoDao = App.i().getCurrDaoSession().getPhotoDao();
                    List<com.paishen.peiniwan.database.Photo> photoList = new ArrayList<>();
                    for (Photo p : response.data) {
                        photoList.add(ModelConverter.mergeOrReplace(null, p, App.i().getUser().getId()));
                    }
                    photoDao.insertOrReplaceInTx(photoList);
                    initAlbumPhoto(false);
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    LogUtil.e("MainProfileLayout requestUserGetPhoto() /n" + response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                //
            }
        });
    }

    public void initAlbumPhoto(boolean byInternetRequest) {
        PhotoDao photoDao = App.i().getCurrDaoSession().getPhotoDao();
        List<com.paishen.peiniwan.database.Photo> photoList = photoDao.queryBuilder().where(PhotoDao.Properties.UserId.eq(App.i().getUser().getId())).orderDesc(PhotoDao.Properties.Id).limit(4).list();
        if (photoList != null && photoList.size() > 0) {
            layAlbumInfo.setVisibility(View.VISIBLE);
            txAlbumInfo.setVisibility(View.GONE);
            imgPhoto1.setVisibility(View.GONE);
            imgPhoto2.setVisibility(View.GONE);
            imgPhoto3.setVisibility(View.GONE);
            imgPhoto4.setVisibility(View.GONE);

            for (int i = 0; i < photoList.size(); i++) {
                if (i == 0) {
                    imgPhoto1.setVisibility(View.VISIBLE);
                    Glide.with(getContext()).load(photoList.get(0).getPhoto_url()).centerCrop().into(imgPhoto1);
                } else if (i == 1) {
                    imgPhoto2.setVisibility(View.VISIBLE);
                    Glide.with(getContext()).load(photoList.get(1).getPhoto_url()).centerCrop().into(imgPhoto2);
                } else if (i == 2) {
                    imgPhoto3.setVisibility(View.VISIBLE);
                    Glide.with(getContext()).load(photoList.get(2).getPhoto_url()).centerCrop().into(imgPhoto3);
                } else if (i == 3) {
                    imgPhoto4.setVisibility(View.VISIBLE);
                    Glide.with(getContext()).load(photoList.get(3).getPhoto_url()).centerCrop().into(imgPhoto4);
                } else {
                    break;
                }
            }
        } else {
            if (byInternetRequest) requestUserGetPhoto();
            layAlbumInfo.setVisibility(View.GONE);
            txAlbumInfo.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 计算个人信息完整度
     * 核心资料 30%{@link com.paishen.peiniwan.database.User#head_img_url} {@link com.paishen.peiniwan.database.User#nickname} {@link com.paishen.peiniwan.database.User#intro} <br/>
     * 基本资料 50%{@link com.paishen.peiniwan.database.User#height} {@link com.paishen.peiniwan.database.User#weight} {@link com.paishen.peiniwan.database.User#age}{@link com.paishen.peiniwan.database.User#profession} {@link com.paishen.peiniwan.database.User#degree} {@link com.paishen.peiniwan.database.User#constellation} {@link com.paishen.peiniwan.database.User#city} {@link com.paishen.peiniwan.database.User#salary}  <br/>
     * 辅助资料 20% {@link com.paishen.peiniwan.database.User#tags} [爱好-技能-性格]
     */
    public int calcUserDataIntegrity(com.paishen.peiniwan.database.User u) {
        float result = 0;
        float part1 = 30f / 3;
        if (!TextUtils.isEmpty(u.getHead_img_url())) result += part1;
        if (!TextUtils.isEmpty(u.getNickname())) result += part1;
        if (!TextUtils.isEmpty(u.getIntro())) result += part1;
        float part2 = 50f / 8;
        if (!TextUtils.isEmpty(u.getHeight())) result += part2;
        if (!TextUtils.isEmpty(u.getWeight())) result += part2;
        if (!TextUtils.isEmpty(u.getAge())) result += part2;
        if (!TextUtils.isEmpty(u.getProfession())) result += part2;
        if (!TextUtils.isEmpty(u.getDegree())) result += part2;
        if (!TextUtils.isEmpty(u.getConstellation())) result += part2;
        if (!TextUtils.isEmpty(u.getCity())) result += part2;
        if (!TextUtils.isEmpty(u.getSalary())) result += part2;
        // if (!TextUtils.isEmpty(u.getAffective())) result += part2; // 取消此项
        float part3 = 20f / 3;
        if (!TextUtils.isEmpty(u.getTags())) {
            List<UserTag> userTagList = App.i().getGson().fromJson(new String(Base64.decode(u.getTags(), Base64.DEFAULT)), new TypeToken<List<UserTag>>() {
            }.getType());
            if (userTagList != null && userTagList.size() >= 3) { // default size is 3
                if (userTagList.get(0).tag_name.length != 0) result += part3;
                if (userTagList.get(1).tag_name.length != 0) result += part3;
                if (userTagList.get(2).tag_name.length != 0) result += part3;
            }
        }

        if (result > 99) result = 100;
        return (int) result;
    }
}
